<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha256-xejo6yLi6vGtAjcMIsY8BHdKsLg7QynVlFMzdQgUuy8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"gz1234.gitee.io","root":"/","images":"/images","scheme":"Gemini","darkmode":true,"version":"8.12.3","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"flat"},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="什么是Redux我们一直通过属性来进行组件中的数据传递,这种模式是非常脆弱的。在日常的开发中经常会遇到非父子组件传递的场景。原来的方式是找到共同的父级进行数据交互，这时通信就变得比较麻烦  store reducer action dispatch 单项数据流 不可变值 异步请求中间件 redux-thunk redux-sage redux-promise  我们先通过一个简单的例子实现一下re">
<meta property="og:type" content="article">
<meta property="og:title" content="Redux">
<meta property="og:url" content="https://gz1234.gitee.io/2020/10/23/react%E7%AC%94%E8%AE%B0/Redux%E5%BA%94%E7%94%A8/index.html">
<meta property="og:site_name" content="郭泽">
<meta property="og:description" content="什么是Redux我们一直通过属性来进行组件中的数据传递,这种模式是非常脆弱的。在日常的开发中经常会遇到非父子组件传递的场景。原来的方式是找到共同的父级进行数据交互，这时通信就变得比较麻烦  store reducer action dispatch 单项数据流 不可变值 异步请求中间件 redux-thunk redux-sage redux-promise  我们先通过一个简单的例子实现一下re">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-10-23T02:07:09.000Z">
<meta property="article:modified_time" content="2023-03-20T09:21:30.604Z">
<meta property="article:author" content="郭泽">
<meta property="article:tag" content="react 基础">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gz1234.gitee.io/2020/10/23/react%E7%AC%94%E8%AE%B0/Redux%E5%BA%94%E7%94%A8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://gz1234.gitee.io/2020/10/23/react%E7%AC%94%E8%AE%B0/Redux%E5%BA%94%E7%94%A8/","path":"2020/10/23/react笔记/Redux应用/","title":"Redux"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Redux | 郭泽</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">郭泽</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFRedux"><span class="nav-number">1.</span> <span class="nav-text">什么是Redux</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#redux%E7%9A%84%E7%90%86%E8%A7%A3-%E6%8F%90%E4%BE%9B%E7%9A%84API"><span class="nav-number">2.</span> <span class="nav-text">redux的理解 提供的API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E7%BB%9F%E4%B8%80%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86"><span class="nav-number">2.1.</span> <span class="nav-text">1).统一数据管理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%AE%9E%E7%8E%B0dispatch"><span class="nav-number">2.2.</span> <span class="nav-text">2).实现dispatch</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-createStore%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.3.</span> <span class="nav-text">3).createStore的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-reducer%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.4.</span> <span class="nav-text">4).reducer的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E8%AE%A2%E9%98%85%E5%87%BD%E6%95%B0"><span class="nav-number">2.5.</span> <span class="nav-text">5).订阅函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BA%94%E7%94%A8redux-js%E5%AE%9E%E7%8E%B0counter"><span class="nav-number">3.</span> <span class="nav-text">2.应用redux+js实现counter</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%BA%94%E7%94%A8redux-react%E5%AE%9E%E7%8E%B0counter"><span class="nav-number">4.</span> <span class="nav-text">3.应用redux+react实现counter</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">郭泽</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">51</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gz1234.gitee.io/2020/10/23/react%E7%AC%94%E8%AE%B0/Redux%E5%BA%94%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="郭泽">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郭泽">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Redux | 郭泽">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Redux
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-10-23 10:07:09" itemprop="dateCreated datePublished" datetime="2020-10-23T10:07:09+08:00">2020-10-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-03-20 17:21:30" itemprop="dateModified" datetime="2023-03-20T17:21:30+08:00">2023-03-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="什么是Redux"><a href="#什么是Redux" class="headerlink" title="什么是Redux"></a>什么是Redux</h2><p>我们一直通过属性来进行组件中的数据传递,这种模式是非常脆弱的。在日常的开发中经常会遇到非父子组件传递的场景。原来的方式是找到共同的父级进行数据交互，这时通信就变得比较麻烦</p>
<ul>
<li>store</li>
<li>reducer</li>
<li>action</li>
<li>dispatch</li>
<li>单项数据流 不可变值</li>
<li>异步请求中间件 redux-thunk redux-sage redux-promise</li>
</ul>
<p>我们先通过一个简单的例子实现一下redux的工作模式:</p>
<h2 id="redux的理解-提供的API"><a href="#redux的理解-提供的API" class="headerlink" title="redux的理解 提供的API"></a>redux的理解 提供的API</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">createStore()</span><br><span class="line">applyMiddleWare()</span><br><span class="line">combineReducers()</span><br><span class="line">store.getState()/dispatch()/subscribe()</span><br></pre></td></tr></table></figure>

<h3 id="1-统一数据管理"><a href="#1-统一数据管理" class="headerlink" title="1).统一数据管理"></a>1).统一数据管理</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> state = &#123;</span><br><span class="line">  title:&#123;<span class="attr">color</span>:<span class="string">&#x27;red&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;标题&#x27;</span>&#125;,</span><br><span class="line">  content:&#123;<span class="attr">color</span>:<span class="string">&#x27;green&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;内容&#x27;</span>&#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderContent</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> content = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;.content&#x27;</span>);</span><br><span class="line">  content.innerHTML = state.content.text;</span><br><span class="line">  content.style.color = state.content.color;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderTitle</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> title = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;.title&#x27;</span>);</span><br><span class="line">  title.innerHTML = state.title.text;</span><br><span class="line">  title.style.color = state.title.color;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderApp</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  renderContent();</span><br><span class="line">  renderTitle()</span><br><span class="line">&#125;</span><br><span class="line">renderApp();</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们可以将renderContent,renderTitle看成两个组件将所需的数据提取到state中统一进行管理。当渲染后我们希望更改状态，封装更改状态的方法(dispatch)</p>
</blockquote>
<a id="more"></a>
<h3 id="2-实现dispatch"><a href="#2-实现dispatch" class="headerlink" title="2).实现dispatch"></a>2).实现dispatch</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> CHANGE_TITLE_TEXT = <span class="string">&#x27;CHANGE_TITLE_TEXT&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (action.type)&#123;</span><br><span class="line">    <span class="keyword">case</span> CHANGE_TITLE_TEXT:</span><br><span class="line">      state = &#123;...state,<span class="attr">title</span>:&#123;...state.title,<span class="attr">text</span>:action.text&#125;&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  dispatch(&#123;<span class="attr">type</span>:CHANGE_TITLE_TEXT,<span class="attr">text</span>:<span class="string">&#x27;hello&#x27;</span>&#125;);</span><br><span class="line">  renderApp();</span><br><span class="line">&#125;,<span class="number">1000</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>不要直接更改状态而是使用dispatch方法进行状态的更改,派发一个带有type的属性来进行状态的更改，但是依然无法阻止用户更改状态.</p>
</blockquote>
<h3 id="3-createStore的实现"><a href="#3-createStore的实现" class="headerlink" title="3).createStore的实现"></a>3).createStore的实现</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> CHANGE_TITLE_TEXT = <span class="string">&#x27;CHANGE_TITLE_TEXT&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createStore</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> state = &#123;</span><br><span class="line">    title:&#123;<span class="attr">color</span>:<span class="string">&#x27;red&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;标题&#x27;</span>&#125;,</span><br><span class="line">    content:&#123;<span class="attr">color</span>:<span class="string">&#x27;green&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;内容&#x27;</span>&#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">let</span> getState = <span class="function">() =&gt;</span> <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(state)); <span class="comment">// 创造一份和状态同样的对象给外界来用</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (action.type)&#123;</span><br><span class="line">      <span class="keyword">case</span> CHANGE_TITLE_TEXT:</span><br><span class="line">        state = &#123;...state,<span class="attr">title</span>:&#123;...state.title,<span class="attr">text</span>:action.text&#125;&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    dispatch,</span><br><span class="line">    getState,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> store = createStore(); <span class="comment">// 拿到createStore中返回的对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderContent</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> content = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;.content&#x27;</span>);</span><br><span class="line">  content.innerHTML = store.getState().content.text;</span><br><span class="line">  content.style.color = store.getState().content.color;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderTitle</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> title = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;.title&#x27;</span>);</span><br><span class="line">  title.innerHTML = store.getState().title.text;</span><br><span class="line">  title.style.color = store.getState().title.color;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderApp</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  renderContent();</span><br><span class="line">  renderTitle()</span><br><span class="line">&#125;</span><br><span class="line">renderApp();</span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  store.dispatch(&#123;<span class="attr">type</span>:CHANGE_TITLE_TEXT,<span class="attr">text</span>:<span class="string">&#x27;hello&#x27;</span>&#125;);</span><br><span class="line">  renderApp();</span><br><span class="line">&#125;,<span class="number">1000</span>);</span><br></pre></td></tr></table></figure>
<!-- more -->
<blockquote>
<p>我们将状态放到了createStore函数中，目的是隔离作用域，并且再内部返回深度克隆的对象，这样用户无法再通过外界更改状态。但是状态应该由我们自身来控制，应该是外界传入的，所以要将状态拿出createStore。并且判断的逻辑也应该由我们自己来编写</p>
</blockquote>
<h3 id="4-reducer的实现"><a href="#4-reducer的实现" class="headerlink" title="4).reducer的实现"></a>4).reducer的实现</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> CHANGE_TITLE_TEXT = <span class="string">&#x27;CHANGE_TITLE_TEXT&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createStore</span>(<span class="params">reducer</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> state;</span><br><span class="line">  <span class="keyword">let</span> getState = <span class="function">() =&gt;</span> <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(state));</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123; </span><br><span class="line">    state  = reducer(state,action);<span class="comment">//获取对应的状态覆盖掉store中的状态</span></span><br><span class="line">  &#125;</span><br><span class="line">  dispatch(&#123;&#125;); <span class="comment">// 默认传入空对象获取reducer返回的默认结果</span></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    dispatch,</span><br><span class="line">    getState,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> initState = &#123;</span><br><span class="line">  title:&#123;<span class="attr">color</span>:<span class="string">&#x27;red&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;标题&#x27;</span>&#125;,</span><br><span class="line">  content:&#123;<span class="attr">color</span>:<span class="string">&#x27;green&#x27;</span>,<span class="attr">text</span>:<span class="string">&#x27;内容&#x27;</span>&#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// reducer应该具有默认状态,当更改状态后使用最新的状态</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=initState,action</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (action.type)&#123;</span><br><span class="line">    <span class="keyword">case</span> CHANGE_TITLE_TEXT:</span><br><span class="line">      <span class="keyword">return</span> &#123;...state,<span class="attr">title</span>:&#123;...state.title,<span class="attr">text</span>:action.text&#125;&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> state</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>此时我们已将需要自己处理的逻辑提取出来，但是我们每次dispatch时都需要自己触发视图的更新,我们希望采用发布订阅来实现。</p>
</blockquote>
<h3 id="5-订阅函数"><a href="#5-订阅函数" class="headerlink" title="5).订阅函数"></a>5).订阅函数</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createStore</span>(<span class="params">reducer</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> state;</span><br><span class="line">  <span class="keyword">let</span> listeners = []; <span class="comment">// 放置所有订阅的函数</span></span><br><span class="line">  <span class="keyword">let</span> getState = <span class="function">() =&gt;</span> <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(state));</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">    state  = reducer(state,action);</span><br><span class="line">    listeners.forEach(<span class="function"><span class="params">item</span>=&gt;</span>item());<span class="comment">//每次派发后执行订阅的函数</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> subscribe = <span class="function">(<span class="params">fn</span>)=&gt;</span>&#123; <span class="comment">//主要用于订阅事件</span></span><br><span class="line">    listeners.push(fn);</span><br><span class="line">    <span class="keyword">return</span> <span class="function">()=&gt;</span>&#123; <span class="comment">//返回一个移除监听的方法</span></span><br><span class="line">      listeners = listeners.filter(<span class="function"><span class="params">l</span>=&gt;</span>l!==fn);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  dispatch(&#123;&#125;);</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    dispatch,</span><br><span class="line">    getState,</span><br><span class="line">    subscribe</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">store.subscribe(renderApp); <span class="comment">//通过suscribe订阅派发时需要触发的函数</span></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  store.dispatch(&#123;<span class="attr">type</span>:CHANGE_TITLE_TEXT,<span class="attr">text</span>:<span class="string">&#x27;hello&#x27;</span>&#125;);</span><br><span class="line">&#125;,<span class="number">1000</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>此时我们redux中常用的方法已经封装完成！^_^,我们将封装好的逻辑抽离成redux.js</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createStore</span>(<span class="params">reducer</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> state;</span><br><span class="line">  <span class="keyword">let</span> listeners = []; <span class="comment">// 放置所有订阅的函数</span></span><br><span class="line">  <span class="keyword">let</span> getState = <span class="function">() =&gt;</span> <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(state));</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">    state  = reducer(state,action);</span><br><span class="line">    listeners.forEach(<span class="function"><span class="params">item</span>=&gt;</span>item());<span class="comment">//每次派发后执行订阅的函数</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> subscribe = <span class="function">(<span class="params">fn</span>)=&gt;</span>&#123; <span class="comment">//主要用于订阅事件</span></span><br><span class="line">    listeners.push(fn);</span><br><span class="line">    <span class="keyword">return</span> <span class="function">()=&gt;</span>&#123; <span class="comment">//返回一个移除监听的方法</span></span><br><span class="line">      listeners = listeners.filter(<span class="function"><span class="params">l</span>=&gt;</span>l!==fn);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  dispatch(&#123;&#125;);</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    dispatch,</span><br><span class="line">    getState,</span><br><span class="line">    subscribe</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-应用redux-js实现counter"><a href="#2-应用redux-js实现counter" class="headerlink" title="2.应用redux+js实现counter"></a>2.应用redux+js实现counter</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&lt;p id=<span class="string">&quot;container&quot;</span>&gt;&lt;/p&gt;</span><br><span class="line">&lt;button id=<span class="string">&quot;add&quot;</span>&gt;+&lt;/button&gt;</span><br><span class="line">&lt;button id=<span class="string">&quot;minus&quot;</span>&gt;-&lt;/button&gt;</span><br><span class="line">&lt;script src=<span class="string">&quot;redux.js&quot;</span>&gt;&lt;/script&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">  <span class="keyword">const</span> ADD = <span class="string">&#x27;ADD&#x27;</span>;</span><br><span class="line">  <span class="keyword">const</span> MINUS = <span class="string">&#x27;MINUS&#x27;</span>;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;number:<span class="number">0</span>&#125;,action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (action.type)&#123;</span><br><span class="line">      <span class="keyword">case</span> ADD:</span><br><span class="line">        <span class="keyword">return</span> &#123;<span class="attr">number</span>:state.number + action.amount&#125;;</span><br><span class="line">      <span class="keyword">case</span> MINUS:</span><br><span class="line">        <span class="keyword">return</span> &#123;<span class="attr">number</span>:state.number - action.amount&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> store = createStore(reducer);</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">render</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    container.innerHTML = store.getState().number</span><br><span class="line">  &#125;</span><br><span class="line">  render();</span><br><span class="line">  store.subscribe(render);</span><br><span class="line">  add.addEventListener(<span class="string">&#x27;click&#x27;</span>,<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    store.dispatch(&#123;<span class="attr">type</span>:ADD,<span class="attr">amount</span>:<span class="number">1</span>&#125;)</span><br><span class="line">  &#125;,<span class="literal">false</span>);</span><br><span class="line">  minus.addEventListener(<span class="string">&#x27;click&#x27;</span>,<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    store.dispatch(&#123;<span class="attr">type</span>:MINUS,<span class="attr">amount</span>:<span class="number">2</span>&#125;)</span><br><span class="line">  &#125;,<span class="literal">false</span>)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>由此我们使用了自己的redux库链接了原生js进行使用。</p>
</blockquote>
<h2 id="3-应用redux-react实现counter"><a href="#3-应用redux-react实现counter" class="headerlink" title="3.应用redux+react实现counter"></a>3.应用redux+react实现counter</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React,&#123;Component&#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"><span class="keyword">import</span> ReactDOM,&#123;render&#125; <span class="keyword">from</span> <span class="string">&#x27;react-dom&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;createStore&#125; <span class="keyword">from</span> <span class="string">&#x27;./redux&#x27;</span></span><br><span class="line"><span class="keyword">const</span> ADD = <span class="string">&#x27;ADD&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> MINUS = <span class="string">&#x27;MINUS&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;number:<span class="number">0</span>&#125;,action</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (action.type)&#123;</span><br><span class="line">    <span class="keyword">case</span> ADD:</span><br><span class="line">      <span class="keyword">return</span> &#123;<span class="attr">number</span>:state.number + action.amount&#125;;</span><br><span class="line">    <span class="keyword">case</span> MINUS:</span><br><span class="line">      <span class="keyword">return</span> &#123;<span class="attr">number</span>:state.number - action.amount&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> store = createStore(reducer);</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Counter</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">super</span>();</span><br><span class="line">    <span class="built_in">this</span>.state = &#123;<span class="attr">number</span>:store.getState().number&#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">componentDidMount</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    store.subscribe( <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.setState(&#123;<span class="attr">number</span>:store.getState().number&#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">  handleAddClick=<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    store.dispatch(&#123;<span class="attr">type</span>:ADD,<span class="attr">amount</span>:<span class="number">1</span>&#125;);</span><br><span class="line">  &#125;;</span><br><span class="line">  handleMinusClick=<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    store.dispatch(&#123;<span class="attr">type</span>:MINUS,<span class="attr">amount</span>:<span class="number">1</span>&#125;);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &lt;div&gt;</span><br><span class="line">      &lt;p&gt;&#123;<span class="built_in">this</span>.state.number&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="built_in">this</span>.handleAddClick&#125;&gt;+&lt;/button&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="built_in">this</span>.handleMinusClick&#125;&gt;-&lt;/button&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ReactDOM.render(<span class="xml"><span class="tag">&lt;<span class="name">Counter</span>/&gt;</span></span>,<span class="built_in">window</span>.root);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们将redux数据映射到了组件自己的状态，并且订阅了setState事件。每次状态更新时都会重新刷新组件</p>
</blockquote>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react-%E5%9F%BA%E7%A1%80/" rel="tag"># react 基础</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2020/10/22/react%E7%AC%94%E8%AE%B0/React%E8%B7%AF%E7%94%B1/" rel="prev" title="react 路由的使用">
                  <i class="fa fa-chevron-left"></i> react 路由的使用
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2020/10/24/react%E7%AC%94%E8%AE%B0/Redux%E6%B7%B1%E5%85%A5/" rel="next" title="react Redux深入">
                  react Redux深入 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">郭泽</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>

  <script class="next-config" data-name="pdf" type="application/json">{"object_url":{"url":"https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.2.8/pdfobject.min.js","integrity":"sha256-tu9j5pBilBQrWSDePOOajCUdz6hWsid/lBNzK4KgEPM="},"url":"/lib/pdf/web/viewer.html"}</script>
  <script src="/js/third-party/tags/pdf.js"></script>

  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.1.3/mermaid.min.js","integrity":"sha256-TIYL00Rhw/8WaoUhYTLX9SKIEFdXxg+yMWSLVUbhiLg="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>

  <script src="/js/third-party/fancybox.js"></script>


  





</body>
</html>
